/* eslint-disable func-names */
/* eslint-disable no-plusplus */
/* eslint-disable import/extensions */
import ElEditable from '@components/el-editable';
import { throttle, isObject } from 'lodash';
import {
  submitOrderReturn,
  saveOrderReturn,
  downloadFailUploadDataTH,
  uploadOriginalOrderReturnedProduct,
  getOrderType,
  wholeOrderReturn,
  queryOrderInfo,
  echoReturnProductList,
  salesReturnDetails
} from '@api/m_mall_web_v1.js';
import * as CONSTS from './index.const';
// import { supplierAndContractComponent } from '~/components/after-sale/supplier-and-contract';
import { productsList } from '~/components/after-sale/original-order-products-list';
import invoiceInfo from '~/components/after-sale/invoice-info/index.vue';
import reason from '~/components/after-sale/reason/index.vue';
import addressFunc from '~/components/after-sale/address-func/index.vue';
import { IndexService } from './index.service';

const indexService = new IndexService();

export default {
  name: 'purchaseReturnOrder',
  provide: {
    downloadFailUploadData: downloadFailUploadDataTH,
    uploadProduct: uploadOriginalOrderReturnedProduct,
    templateDownLoad:
      'https://md.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/yjqoyms1x7cuwb1iv3s0rzwcj3cbu7fv.xlsx'
  },
  data() {
    return {
      ...CONSTS,
      active_index: 1,
      // 用于接口使用的绑定数据
      submit_data: {
        // 第一步
        supplier_id: '',
        contract_id: '',
        // 第二步产品
        return_goods: [],
        // 第二步原因
        return_reason: {
          reason_sel: '',
          reason_text: '',
          reason_imgs: [],
          reason_name: ''
        },
        // 第三步发票信息
        invoice_info: {
          receive_invoice: false,
          financial_entry: false
        },
        // 第三步地址
        full_address: {},
        orderCode: '',
        orderCodeRelate: '',
        orderDetailId: '',
        orderId: '',
        order_type_key: '',
        supplier_data: {},
        contract_data: {}
      },
      address_id: '',
      // 用于页面渲染使用的数据
      render_data: {
        order_type_rows: []
      },
      // 用于各种状态的数据
      status: {
        isEdit: false,
        isFirstMount: true,
        dialogVisible: false,
        submit_loading: false
      },
      idKey: {
        orderCode: '',
        orderCodeRelate: '',
        orderDetailId: '',
        orderId: ''
      }
    };
  },
  components: {
    ElEditable,
    // supplierAndContractComponent,
    productsList,
    reason,
    invoiceInfo,
    addressFunc
  },
  mounted() {
    // 初始化导航栏按钮
    this.initGlobalBtn();
  },
  created() {
    // 编辑模式
    this.getOrderDetailInfo();
  },
  computed: {
    queryParams() {
      return {
        orderId: this.$route.query.orderId,
        orderType: this.$route.query.orderType
      };
    }
  },
  methods: {
    addWholeOrderProducts() {
      this.$axios({
        method: 'post',
        url: wholeOrderReturn,
        data: {
          orderCode: this.idKey.orderCodeRelate
        }
      }).then(res => {
        const result = res.data.payload;
        if (result.isPartialReturns === '1') {
          this.$message({
            type: 'warning',
            message: '存在部分退换货，只展示剩余可退换产品'
          });
        }
        if (
          result.returnProductList.content &&
          result.returnProductList.content.length > 0
        ) {
          this.submit_data.return_goods = result.returnProductList.content.map(
            it => ({
              ...it,
              productCount: Number(it.returnCount) || 1,
              mixsIds:
                it.orginalOrderCode +
                it.seqNo +
                it.productCode +
                it.batchNo +
                it.validDate +
                it.referencePrice
            })
          );
        } else {
          this.$message({ type: 'warning', message: '没有可以整单退货的产品' });
        }
      });
    },
    getOrderDetailInfo() {
      this.$axios({
        method: 'post',
        url: queryOrderInfo,
        data: {
          orderId: this.queryParams.orderId
        }
      }).then(res => {
        const result = res.data.payload;
        this.busModel = result.busModel;
        // 这里和新建有些不同的地方就是，这里不用通过id反向匹配经销商和合同，所以，直接赋值就好了
        this.submit_data.supplier_data = result.supplierVo;
        this.submit_data.contract_data = result.contractVo;
        this.getOrderTypeRows(result);
        if (String(this.queryParams.orderType) === '2') {
          // 承运方式
          this.submit_data.carryway_id = String(result.transportType || '');
          this.getDetailData(result);
          this.getEchoReturnProductList(result);
          this.status.isEdit = true;
        } else {
          // 新建的话，orderCodeRelate就是orderCode
          this.idKey.orderCodeRelate = result.orderCode;
          // 给submit中的对应字段赋值，是为了可以传递给自组件使用。
          this.submit_data.orderCodeRelate = result.orderCode;
        }
      });
    },
    getDetailData(params) {
      this.$axios({
        url: salesReturnDetails,
        method: 'post',
        data: {
          orderId: params.orderId
        }
      }).then(res => {
        const result = res.data.payload ? res.data.payload : {};
        if (String(this.queryParams.orderType) === '2') {
          // 编辑的话，orderCodeRelate就是orderCodeRelate
          this.idKey.orderCodeRelate = result.orderData.orderCodeRelate;
          // 给submit中的对应字段赋值，是为了可以传递给自组件使用。
          this.submit_data.orderCodeRelate = result.orderData.orderCodeRelate;
        }
        this.render_data.orderData = result.orderData;
        // 设置地址
        this.address_id = result.orderReceiver.userAddressId;
        this.submit_data.full_address = {
          ...result.orderReceiver,
          userName: result.orderReceiver.addressee,
          userPhone: result.orderReceiver.addressPhone
        };
        this.idKey.orderCode = result.orderData.orderCode;
        this.idKey.orderId = result.orderData.orderId;
        this.idKey.orderDetailId = result.orderData.orderDetailId;
        // 设置发票信息
        this.submit_data.invoice_info.financial_entry =
          result.orderData.financialEntry === '1';
        this.submit_data.invoice_info.receive_invoice =
          result.orderData.receiptInvoice === '1';
        // 设置退货原因
        this.submit_data.return_reason.reason_sel =
          result.orderData.returnReasonCode;
        this.submit_data.return_reason.reason_text =
          result.orderData.returnReasonDetail;
        this.submit_data.return_reason.reason_name =
          result.orderData.returnReasonName;
        this.submit_data.return_reason.reason_imgs = result.commonFile.map(
          item => item.fileUrl
        );
      });
    },
    getEchoReturnProductList(result) {
      this.$axios({
        method: 'post',
        url: echoReturnProductList,
        data: {
          orderCode: result.orderCode
        }
      }).then(res => {
        const data = res.data.payload?.content;
        this.submit_data.return_goods = data.map(it => ({
          ...it,
          attribute1: it.model || it.specs,
          productUnitName: it.productUnit,
          productCount: Number(it.returnQuantity) || 1,
          returnCount: Number(it.returnableQuantity),
          referencePrice: it.productPrice,
          mixsIds:
            it.orginalOrderCode +
            it.seqNo +
            it.productCode +
            it.batchNo +
            it.validDate +
            it.referrencePrice
        }));
        this.isReturnProductsOccupy(this.submit_data.return_goods);
      });
    },
    // 判断退货产品是否被其他订单占用
    isReturnProductsOccupy(products) {
      const flag = products.some(
        item => Number(item.returnableQuantity) < Number(item.returnQuantity)
      );
      if (flag) {
        this.$alert('暂存的退货产品被别的订单使用，请订正退货产品', '', {
          confirmButtonText: '知道了',
          callback: () => {
            this.submit_data.return_goods = this.submit_data.return_goods.filter(
              item => Number(item.returnableQuantity) > 0
            );
          }
        });
      }
    },
    getOrderTypeRows(result) {
      this.$axios({
        method: 'post',
        url: getOrderType,
        data: {
          busModel: result.busModel,
          supplierCode: '000'
        }
      }).then(res => {
        const newResult = res.data.payload || {};
        this.render_data.order_type_rows = newResult;
        this.submit_data.order_type_key = this.render_data.order_type_rows.find(
          item => item.orderTypeName.includes('退货')
        ).ddbm;
      });
    },
    getSeledAddress(val) {
      this.submit_data.full_address = val;
    },
    // 全局性初始化配置
    // 导航栏按钮
    // 上一步
    onPrev() {
      if (this.active_index-- <= 1) this.active_index = 1;
      this.initGlobalBtn();
    },
    // 下一步
    onNext() {
      const verifyResult = indexService.verifyStep(
        this.active_index,
        this.submit_data
      );
      if (verifyResult.pass === true) {
        if (this.active_index++ >= 2) this.active_index = 2;
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verifyResult.message
        });
      }
      this.initGlobalBtn();
    },
    // 暂存
    onSaveDraft() {
      const verifyResult = indexService.verifyStep(
        this.active_index,
        this.submit_data
      );
      if (verifyResult.pass === true) {
        this.saveProgress();
      } else {
        this.$notify({
          type: 'warning',
          title: '请注意',
          message: verifyResult.message
        });
      }
    },
    saveProgress: throttle(
      function() {
        this.$axios({
          url: saveOrderReturn,
          method: 'post',
          data: this.splitSubmitDataBySteps()
        })
          .then(res => {
            const result = isObject(res.data.payload) ? res.data.payload : {};
            this.idKey.orderCode = result.orderCode;
            this.idKey.orderId = result.orderId;
            this.idKey.orderDetailId = result.orderDetailId;
            this.$message({
              type: 'success',
              message: '暂存成功'
            });
          })
          .catch(() => {
            this.$message({
              type: 'warning',
              message: '暂存失败'
            });
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    getReasonName(reasonName) {
      this.submit_data.return_reason.reason_name = reasonName;
    },
    reStructSubmitData() {
      return {
        busModel: '1',
        financialEntry: this.submit_data.invoice_info.financial_entry
          ? '1'
          : '2',
        receiptInvoice: this.submit_data.invoice_info.receive_invoice
          ? '1'
          : '2',
        returnReasonCode: this.submit_data.return_reason.reason_sel,
        returnReason: this.submit_data.return_reason.reason_name,
        returnReasonDetail: this.submit_data.return_reason.reason_text,
        supplierVo: this.submit_data.supplier_data, // 供应商
        contractVo: this.submit_data.contract_data, // 合同
        saveProductVO: this.submit_data.return_goods, // 采购产品
        addressResDto: this.submit_data.full_address, // 地址
        commonFileForms: this.submit_data.return_reason.reason_imgs.map(
          item => {
            const name = item.substring(item.lastIndexOf('/') + 1);
            return {
              fileName: name.split('.')[0],
              fileType: name.split('.')[1],
              fileUrl: item
            };
          }
        ), // 原因图片
        orderCode: this.idKey.orderCode, // 订单编码
        orderCodeRelate: this.idKey.orderCodeRelate,
        orderDetailId: this.idKey.orderDetailId, // 订单详情id
        orderId: this.idKey.orderId, // 订单id
        orderType: this.submit_data.order_type_key,
        orderTypeId: this.render_data.order_type_rows.find(
          item => item.ddbm === this.submit_data.order_type_key
        ).orderTypeId,
        createType: 2 // 1独立创建，2原单创建
      };
    },
    onSubmit: throttle(
      function() {
        this.submit_loading = true;
        this.$axios({
          url: submitOrderReturn,
          method: 'post',
          data: this.reStructSubmitData()
        })
          .then(res => {
            if (res.data.code === '0') {
              this.$router.push('/purchase-order/wholesale/list');
              this.$message({
                message: '订单提交成功',
                type: 'success'
              });
            }
          })
          .catch(err => {
            if (err.data.code === '200001') {
              this.$router.push('/purchase-order/wholesale/list');
            }
          })
          .finally(() => {
            this.status.dialogVisible = false;
            this.status.submit_loading = false;
          });
      },
      3000,
      {
        leading: true,
        trailing: false
      }
    ),
    // 打开确认提交弹窗
    showConfirmDialog() {
      const verifyResult = indexService.verifyStep(2, this.submit_data);
      if (verifyResult.pass === true) {
        this.status.dialogVisible = true;
        // this.saveTheData();
      } else {
        this.$notify({
          title: '必填项',
          message: verifyResult.message,
          type: 'warning'
        });
      }
    },
    initGlobalBtn() {
      const btnObj = {
        type: 'btn',
        arr: []
      };
      const saveDraftBtn = {
        val: '暂存',
        handle: this.onSaveDraft
      };
      const prevBtn = {
        type: 'primary',
        val: '上一步',
        handle: this.onPrev
      };
      const nextBtn = {
        type: 'primary',
        val: '下一步',
        handle: this.onNext
      };
      const submitBtn = {
        type: 'primary',
        val: '提交',
        handle: this.showConfirmDialog
      };
      if (this.active_index !== 1) {
        btnObj.arr.push(prevBtn);
      }
      if (this.active_index !== 2) {
        btnObj.arr.push(nextBtn);
      } else {
        btnObj.arr.push(submitBtn);
      }
      btnObj.arr.push(saveDraftBtn);
      this.$store.commit('changeLayoutHandle', btnObj);
    },
    splitSubmitDataBySteps() {
      const curStep = this.active_index; // 当前步骤
      // 这里跟submit_data一模一样，下面选择性的赋值
      const splitSubmitData = {
        busModel: '1',
        financialEntry: '',
        receiptInvoice: '',
        returnReason: '',
        returnReasonCode: '',
        returnReasonDetail: '',
        supplierVo: {}, // 供应商
        contractVo: {}, // 合同
        saveProductVO: [], // 采购产品
        addressResDto: {}, // 地址
        commonFileForms: [], // 原因图片
        orderCode: this.idKey.orderCode, // 订单编码
        orderDetailId: this.idKey.orderDetailId, // 订单详情id
        orderId: this.idKey.orderId, // 订单id
        orderCodeRelate: this.idKey.orderCodeRelate,
        orderType: this.submit_data.order_type_key,
        orderTypeId: this.render_data.order_type_rows.find(
          item => item.ddbm === this.submit_data.order_type_key
        ).orderTypeId,
        createType: 2 // 1独立创建，2原单创建
      };
      // 第一步
      // eslint-disable-next-line default-case
      switch (curStep) {
        // // 第一步，只存第一步的合同和供应商
        // case 1:
        //   splitSubmitData.supplierVo = this.submit_data.supplier_data;
        //   splitSubmitData.contractVo = this.submit_data.contract_data;
        //   break;
        // 除了第一步的，还额外需要产品部分
        case 1:
          splitSubmitData.supplierVo = this.submit_data.supplier_data;
          splitSubmitData.contractVo = this.submit_data.contract_data;
          splitSubmitData.saveProductVO = this.submit_data.return_goods;
          splitSubmitData.returnReasonCode = this.submit_data.return_reason.reason_sel;
          splitSubmitData.returnReason = this.submit_data.return_reason.reason_name;
          splitSubmitData.returnReasonDetail = this.submit_data.return_reason.reason_text;
          splitSubmitData.commonFileForms = this.submit_data.return_reason.reason_imgs.map(
            item => {
              const name = item.substring(item.lastIndexOf('/') + 1);
              return {
                fileName: name.split('.')[0],
                fileType: name.split('.')[1],
                fileUrl: item
              };
            }
          );

          break;
        // 第二步就比较简单了
        case 2:
          splitSubmitData.supplierVo = this.submit_data.supplier_data;
          splitSubmitData.contractVo = this.submit_data.contract_data;
          splitSubmitData.saveProductVO = this.submit_data.return_goods;
          splitSubmitData.returnReasonCode = this.submit_data.return_reason.reason_sel;
          splitSubmitData.returnReason = this.submit_data.return_reason.reason_name;
          splitSubmitData.returnReasonDetail = this.submit_data.return_reason.reason_text;
          splitSubmitData.addressResDto = this.submit_data.full_address;
          splitSubmitData.financialEntry = this.submit_data.invoice_info
            .financial_entry
            ? '1'
            : '2';
          splitSubmitData.receiptInvoice = this.submit_data.invoice_info
            .receive_invoice
            ? '1'
            : '2';

          splitSubmitData.commonFileForms = this.submit_data.return_reason.reason_imgs.map(
            item => {
              const name = item.substring(item.lastIndexOf('/') + 1);
              return {
                fileName: name.split('.')[0],
                fileType: name.split('.')[1],
                fileUrl: item
              };
            }
          );
          break;
      }
      return splitSubmitData;
    }
  }
};
